<template>
  <el-dialog
    v-if="dialogVisible"
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="35%"
    @closed="afterCloseDialog"
  >
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="dialogForm"
      label-width="140px"
    >
      <el-form-item label="规则名称：" prop="name">
        <el-input v-model="dialogForm.name" placeholder="请输入规则名称" />
      </el-form-item>
      <el-form-item label="适用范围：" prop="scope" class="reset-form-item">
        <tree-select
          class="custom-tree-select"
          v-model="scopedIds"
          :options="graphMapList"
          multiple
          searchable
          clearable
          :default-expand-level="1"
          :limit="3"
          :max-height="200"
          placeholder="请选择适用范围"
          noResultsText="暂无数据"
          noOptionsText="暂无数据"
          @input="updateScope"
        />
      </el-form-item>
      <el-row type="flex">
        <el-form-item label="规则条件：" prop="ruleCondition">
          <el-select
            v-model="dialogForm.ruleCondition"
            placeholder="请选择规则条件"
            style="width: 100%"
          >
            <el-option
              v-for="item in ruleConditions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-form-item label="规则描述：" prop="description">
        <el-input
          v-model="dialogForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入规则描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="confirmDialog">确定</el-button>
    </template>
  </el-dialog>
</template>
<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'OperaRule',
  components: {
    TreeSelect,
  },
  data() {
    return {
      dialogTitle: '新建规则',
      dialogVisible: false,
      isEdit: false,
      dialogForm: {
        name: null,
        scope: null,
        scopeType: null,
        ruleCondition: null,
        description: null,
      },
      scopedIds: [],
      rules: {
        name: [
          { required: true, message: '规则名称不能为空！', trigger: 'blur' },
        ],
        scope: [
          { required: true, message: '适用范围不能为空!', trigger: 'change' },
        ],
        ruleCondition: [
          { required: true, message: '规则条件不能为空！', trigger: 'blur' },
        ],
      },
      graphResList: [], // 请求原数据
      graphMapList: [], // treeSelect使用数据
      // 条件列表
      ruleConditions: [
        { label: '以统计数量最高', value: 1 },
        // { label: "以置信度最高", value: 2 },
        { label: '以最近更新', value: 3 },
      ],
    }
  },
  methods: {
    // 打开弹窗
    openDialog(row) {
      // 请求图谱数据
      this.getGraphList()
      if (row) {
        Object.assign(this.dialogForm, row)
        if (this.dialogForm.scope) {
          try {
            if (this.dialogForm.scopeType === 1) {
              this.scopedIds = ['0']
            } else {
              const arr = JSON.parse(this.dialogForm.scope)
              this.scopedIds = arr.map((i) => i.id)
            }
          } catch {}
        }
        this.isEdit = true
        this.dialogTitle = '编辑规则'
      } else {
        this.dialogTitle = '新建规则'
        this.isEdit = false
        this.dialogForm = {
          name: null,
          scope: null,
          scopeType: null,
          ruleCondition: null,
          description: null,
        };
        this.scopedIds = [];
      }
      this.dialogVisible = true
    },
    // 获取图谱列表
    getGraphList() {
      this.$axios
        .post(this.$api.knowledgeMap.getMapList, {
          graphName: '',
          graphStatus: '0',
          pageNum: '',
          pageSize: '',
        })
        .then((res) => {
          const data = res.data.data
          if (Array.isArray(data.list)) {
            this.graphResList = data.list
            this.graphMapList = [
              {
                id: '0',
                label: '全部图谱',
                children: data.list.map((i) => {
                  return {
                    id: i.projectId,
                    label: i.projectName,
                  }
                }),
              },
            ]
          }
        })
    },
    afterCloseDialog() {
      this.dialogForm = {
        name: null,
        scope: null,
        scopeType: null,
        ruleCondition: null,
        description: null,
      }
      this.scopedIds = []
      this.$refs.ruleFormRef.resetFields()
      // this.$refs.ruleFormRef.resetFields();
    },
    updateScope(ids) {
      if (ids.length === 0) {
        this.dialogForm.scope = null
        this.dialogForm.scopeType = null
      } else if (ids.length === 1 && ids[0] === '0') {
        const arr = this.graphResList.map((i) => {
          return {
            id: i.projectId,
            name: i.projectName,
          }
        })
        this.dialogForm.scope = JSON.stringify(arr)
        this.dialogForm.scopeType = 1
      } else {
        const arr = this.graphResList
          .filter((i) => ids.includes(i.projectId))
          .map((i) => {
            return {
              id: i.projectId,
              name: i.projectName,
            }
          })
        this.dialogForm.scope = JSON.stringify(arr)
        this.dialogForm.scopeType = 0
      }
    },
    // 取消
    closeDialog() {
      this.dialogVisible = false
      this.$refs.ruleFormRef.resetFields()
    },
    confirmDialog() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.submitEdit(this.dialogForm)
          } else {
            this.submitAdd(this.dialogForm)
          }
        } else {
          this.$message.warning('请检查必填项')
        }
      })
    },
    // 新增
    submitAdd(params) {
      this.$axios
        .post(this.$api.knowledgeComputation.fusionRule.addFusionRule, params)
        .then((res) => {
          this.$message.success(res.data.message)
          this.$emit('reload')
          this.dialogVisible = false
        })
    },
    // 编辑
    submitEdit(params) {
      this.$axios
        .put(this.$api.knowledgeComputation.fusionRule.editFusionRule, params)
        .then((res) => {
          this.$message.success(res.data.message)
          this.$emit('reload')
          this.dialogVisible = false
        })
    },
  },
}
</script>
